package com.glodon.paas.databag.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.glodon.paas.databag.controller.PublicController;

/**
 * 负责将公开的数据包跳过后续的sso filter
 * 
 * @author botao.liao
 * 
 */
public class PublicFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestUri = req.getRequestURI();
        // /databag/bag/2c90eb4b3ce60e7a013ce61b90d7000c/resource
        // 从获取资源的url接口中提取databagId
        int prefix = requestUri.indexOf("/bag");
        if (prefix == -1) {
            chain.doFilter(request, response);
            return;
        }
        int start = prefix + 5;
        int end = requestUri.indexOf("/", start);
        if (end == -1) {
            chain.doFilter(request, response);
            return;
        }
        String databagId = requestUri.substring(start, end);
        HttpSession session = req.getSession(false);
        if (session == null) {
            chain.doFilter(request, response);
            return;
        }
        String sDatabagId = (String) session.getAttribute(PublicController.SESSION_PUBLIC_DATABAG);
        if (sDatabagId != null && sDatabagId.equals(databagId)) {
            request.getRequestDispatcher(req.getServletPath() + (req.getPathInfo()==null?"":req.getPathInfo())).forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }

}
